<?php

namespace App\Tools;


class Upload
{
    /**
     * 上传图像(原尺寸上传)
     * @param $file 文件对象
     * @param $path 保存路径文件夹
     * @return string
     */
    public static function uploadImage($file, $path)
    {
        if (!$file || !$path) return result_json(400, '参数错误');
        $url_path = "storage/uploads/images/{$path}";
        $ext_arr = ['jpg', 'jpeg', 'png'];

        if (!$file->isValid()) return result_json(409, '图片无效');
        $client_name = $file->getClientOriginalName();
        $size = $file->getSize();
        $ext = $file->getClientOriginalExtension();
        if (!in_array($ext, $ext_arr)) return result_json(409, '图片格式为jpg,jpeg,png');
        if($size > 2*1024*1024) return result_json(409, '图片大小不能超过2M');

        $new_wame = md5(date("Y-m-d H:i:s") . $client_name) . "." . $ext;
        $path = $file->move($url_path, $new_wame);
        if(!$path) return result_json(500, '上传失败');
        $save_path = $url_path . '/' . $new_wame;
        return result_json(200, '上传成功', ['file_path' => $save_path]);
    }

    /**
     * 上传包
     * @param $file 文件对象
     * @param $path 保存路径文件夹 (例如: 安卓的 app_key/android)
     * @return string
     */
    public static function uploadPackage($file, $path)
    {
        if (!$file || !$path) return result_json(400, '参数错误');
        $url_path = "storage/uploads/packages/{$path}";
        $ext_arr = ['apk', 'ipa'];

        if (!$file->isValid()) return result_json(409, '文件无效');
        $client_name = $file->getClientOriginalName();
        $size = $file->getSize();
        $ext = $file->getClientOriginalExtension();
        if (!in_array($ext, $ext_arr)) return result_json(409, '文件格式为apk, ipa');
        if($size > 200*1024*1024) return result_json(409, '文件大小不能超过200M');

        $new_wame = md5(date("Y-m-d H:i:s") . $client_name) . "." . $ext;
        $path = $file->move($url_path, $new_wame);
        if(!$path) return result_json(500, '上传失败');
        $save_path = $url_path . '/' . $new_wame;
        return result_json(200, '上传成功', ['file_path' => $save_path]);
    }

    /**
     *
     * @param $path
     * @param string $type
     * @return string
     */
    public static function getfileSize($path, $type = 'M')
    {
        if (!is_file($path)) return 0 . $type;
        $size = round(filesize($path) / 1024 / 1024, 2) . $type;
        return $size;
    }
}
